import torch
from torch import Tensor
import numpy as np
from isaacgym.torch_utils import quat_apply, normalize
from typing import Tuple

# @ torch.jit.script
def quat_apply_yaw(quat, vec):  # 将四元数 quat 的旋转限制在水平方向（即仅保留偏航角部分），然后对向量 vec 应用这个旋转。
    quat_yaw = quat.clone().view(-1, 4)
    quat_yaw[:, :2] = 0.
    quat_yaw = normalize(quat_yaw)
    return quat_apply(quat_yaw, vec)

# @ torch.jit.script
def wrap_to_pi(angles): # 将角度值限制在 [−π,π] 范围内
    angles %= 2*np.pi
    angles -= 2*np.pi * (angles > np.pi)
    return angles

# @ torch.jit.script
def torch_rand_sqrt_float(lower, upper, shape, device):
    # type: (float, float, Tuple[int, int], str) -> Tensor
    r = 2*torch.rand(*shape, device=device) - 1
    r = torch.where(r<0., -torch.sqrt(-r), torch.sqrt(r))
    r =  (r + 1.) / 2.
    return (upper - lower) * r + lower

def get_scale_shift(range): # 原始范围是 [range[0], range[1]]，目标范围是 [−1,1]，归一化的值为 scale * (x - shift)
    scale = 2. / (range[1] - range[0])  # 计算缩放因子
    shift = (range[1] + range[0]) / 2.  # 计算偏移量
    return scale, shift

